# Create your views here.
from django.db import DataError
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle, SimpleRateThrottle
from rest_framework.filters import OrderingFilter

from book.models import BookInfo
from .serializers_2 import BookSerializer
from tools.my_pagination import TestPagination, TestPagination2


class BooksView(ListCreateAPIView):
    """
    get:
    返回所有图书信息.

    post:
    新建图书.
    """
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer
    # authentication_classes = (BasicAuthentication,SessionAuthentication)
    # permission_classes = (IsAuthenticated,)

    # 过滤
    throttle_scope = 'books'
    filter_fields = ('btitle', 'bread')

    # 排序
    filter_backends = (OrderingFilter,)
    ordering_fields = ('btitle', 'bpub_date', 'bread')

    # 分页
    pagination_class = TestPagination2

    def list(self, request, *args, **kwargs):
        # 在这里可以添加自己的逻辑
        raise DataError
        return super().list(request, *args, **kwargs)


class BookView(RetrieveUpdateDestroyAPIView):
    """
    get:
    返回图书信息.

    put:
    修改图书.

    delete:
    删除图书.

    patch:
    删除图书.
    """

    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer
    # authentication_classes = (BasicAuthentication,SessionAuthentication)
    # permission_classes = (IsAuthenticatedOrReadOnly,)
    throttle_scope = 'book'


